/*
 * @Author: your name
 * @Date: 2021-02-17 13:47:11
 * @LastEditTime: 2021-05-18 22:16:02
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jianfa-api\utils\utils.js
 */
const { LIMIT } = require("./constant");
const path = require("path");
const fs = require("fs"); //node读取文件模块
const { querySql } = require("../db");
module.exports = {
    /**
     * @description: 添加分页 及 搜索模糊查询
     * @param {Object} params req.body 分页参数
     * @param {String} sql 待处理的sql语句
     * @param {String} table_name 表名
     * @return {String} 添加分页后的sql语句
     */
    async page_sql(params, sql, table_name, isUnion) {
        //where code_name like '%松%' and html like '%习近平%'    isUnion开启关联查询
        let { page, limit } = params;
        if (page) {
            const limits = limit || LIMIT;
            let count_sql = `select count(*) from ${table_name}`;
            let like_sql = "";
            Object.keys(params).forEach((key_name) => {
                if (key_name != "limit" && key_name != "id" && key_name != "page" && key_name != "table_name" && key_name != "sid") {
                    like_sql += `and ${key_name} like '%${params[key_name]}%'`;
                } else if (key_name == "sid") {
                    like_sql = `*** sid='${params[key_name]}'`;
                }
            });
            like_sql = !like_sql ? "" : ` where` + like_sql.substr(3);
            count_sql += like_sql;
            sql += like_sql;
            const { results } = await querySql(count_sql); //查询总条数
            global.all_let.TOTAL = results[0]["count(*)"];
            isUnion
                ? (sql += ` order by ${table_name}.id desc limit ${(page - 1) * limits},${limits}`)
                : (sql += ` order by id desc limit ${(page - 1) * limits},${limits}`);
        }
        return sql;
    },
    /**
     * @description: 根据图片相对路径删除图片
     * @param {String} img_path //数据库中存储的图片路径
     * @return {Promise}
     */
    delImg(img_path) {
        const imgUrl = path.resolve(__dirname, `../${img_path}`);
        return new Promise((resolve, reject) => {
            fs.unlink(imgUrl, (error) => {
                if (error) {
                    console.log("删除本地文件失败", error);
                    return resolve(false);
                }
                console.log("删除文件成功");
                return resolve(true);
            });
        });
    },
};
